<!-- 点单中心 -->
<template>
  <div v-loading="loading">
    <!-- 搜索部分 -->
    <el-card shadow="always" class="ml10 mb10 mt10 ml10">
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="桌号">
            <el-input v-model="searchData.num" placeholder="桌号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="点单人">
            <el-input
              v-model="searchData.people"
              placeholder="点单人"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="时间">
            <el-date-picker
              v-model="searchData.time"
              format="YYYY-MM-DD"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 新增按钮 -->
    <el-button type="primary" @click="handleAdd" class="ml10">开台</el-button>
    <!-- 表格 -->
    <el-card shadow="always" class="ml10 mb10 mt10 ml10">
      <el-row :gutter="12">
        <el-table
          :data="tableData.list"
          border
          style="width: 100%; height: 630px"
          line-height="50px"
        >
          <el-table-column type="index" label="序号" width="180">
          </el-table-column>
          <el-table-column prop="num" label="桌号"> </el-table-column>
          <el-table-column prop="people" label="点单人"> </el-table-column>
          <el-table-column label="时间">
            <template #default="scoped">
              <span>{{ scoped.row.create_time }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scoped">
              <el-button
                v-if="scoped.row.isAddMenu == 1"
                type="primary"
                size="small"
                @click="handleCreat(scoped.row)"
              >
                加单
              </el-button>
              <el-button
                v-else
                type="primary"
                size="small"
                @click="handleCreat(scoped.row)"
              >
                点单
              </el-button>

              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scoped.row)"
              >
                修改台区
              </el-button>
              <!-- <el-button
                type="danger"
                size="small"
                @click="deleteClick(scoped.row)"
                >删除</el-button
              > -->
              <el-button
                type="danger"
                size="small"
                @click="handleOverMonery(scoped.row)"
              >
                结账
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="18"> </el-col>
        <el-col :span="6">
          <el-pagination
            :page-size="searchData.pageSize"
            :size="searchData.pageNum"
            :background="false"
            layout="total, prev, pager, next"
            :total="tableData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
    </el-card>
    <!-- 弹框 -->
    <el-dialog :title="dialogTitle" v-model="dialogFormVisible">
      <el-form :model="formData" :rules="rules" ref="ruleFormRef">
        <el-form-item label="桌号" :label-width="formLabelWidth" prop="num">
          <el-input
            v-model="formData.num"
            autocomplete="off"
            type="number"
            placeholder="桌号"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="点单人"
          :label-width="formLabelWidth"
          prop="people"
        >
          <el-input v-model="formData.people" placeholder="点单人"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel(ruleFormRef)">取 消</el-button>
        <el-button type="primary" @click="onSubmit(ruleFormRef)"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 点单弹框 -->
    <el-dialog title="点单" v-model="dialogOrder">
      <el-form :model="creatOrder" :rules="rules" ref="ruleFormRef">
        <el-form-item label="菜品" :label-width="formLabelWidth" prop="people">
          <el-transfer
            v-model="changeValue"
            filterable
            filter-placeholder="菜单名称"
            :data="skuList"
            :titles="['未选菜单', '已选菜单']"
            :button-texts="['取消', '点单']"
            @change="handleChange"
          />
        </el-form-item>
      </el-form>
      <el-row :gutter="24">
        <el-col :span="8" v-for="item in creatOrderLise" :key="item.id">
          <div class="grid-content ep-bg-purple">
            <div>{{ item.skuName }}:</div>
            <div>
              <el-input-number size="small" v-model="item.num" :min="1" />
            </div>
            <div>￥{{ item.num * item.price }}</div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="18"></el-col>
        <el-col :span="4">总价钱:￥{{ sumMonery }}</el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogOrder = false">取 消</el-button>
        <el-button type="primary" @click="handdleOrderDetail">下 单</el-button>
      </div>
    </el-dialog>
    <!-- 点击结账 -->
    <el-dialog title="结账" v-model="dialogCheckout">
      <el-row :gutter="24">
        <el-col :span="7" v-for="item in historyLis" :key="item.id">
          <div class="grid-content ep-bg-purple">
            <div :style="{ color: item.isNew == 1 ? 'blue' : '' }">
              {{ item.skuName }}:
            </div>
            <div>
              &nbsp &nbsp x
              <span style="color: red">{{ item.num }}</span>
            </div>
            <div style="margin-left: 20px">￥{{ item.num * item.price }}</div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="18"></el-col>
        <el-col :span="4"
          ><div style="font-size: 20px">
            总价钱:￥{{ sumOrderMonery }}
          </div></el-col
        >
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCheckout = false">取 消</el-button>
        <el-button type="primary" @click="handdleOrderOver">结 账</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="PlaceOrderCenter">
import { ref, reactive, onMounted, computed } from 'vue'
import {
  getList,
  creatItem,
  deleteItem,
  editItem,
  getOne,
} from '@/api/test_menu/index'
// import {
//   listtable,
//   gettable,
//   addtable,
//   updatetable,
//   deltable,
// } from '@/api/sku/sku.js'
import {
  listtable,
  addtable,
  addOrder,
  orderOver,
  createCenter,
} from '@/api/sku/sku.js'
import { ElMessageBox, ElMessage } from 'element-plus'
onMounted(() => {
  geTableList()
  geSkuList()
})
const loading = ref(false)
const formData = reactive({
  num: null,
  people: '',
  time: '',
  testMenuId: '',
  isAddMenu: '',
})
const ruleFormRef = ref()
const searchData = reactive({
  num: null,
  people: '',
  pageNum: 1,
  pageSize: 10,
})
const rules = ref({
  num: [{ required: true, message: '桌号号不能为空', trigger: 'blur' }],
  people: [{ required: true, message: '点单人不能为空', trigger: 'blur' }],
})
const dialogFormVisible = ref(false)
const formLabelWidth = '120px'
const tableData = reactive({
  list: [],
  total: 0,
})
const dialogTitle = ref('新增桌号')

//获取列表
const geTableList = async () => {
  loading.value = true
  let params = {
    num: searchData.num,
    people: searchData.people,
    create_time: searchData.time == undefined ? '' : parseTime(searchData.time),
    pageNum: searchData.pageNum,
    pageSize: searchData.pageSize,
  }
  let res = await getList(params)
  loading.value = false
  tableData.list = res.data.list
  tableData.total = res.data.total
}
//==========商品List==========================
const skuList = ref([])
const changeValue = ref([])

//获取商品列表
const geSkuList = async () => {
  let params = {
    skuName: '',
    price: '',
    quantity: '',
    create_time: '',
  }
  let res = await listtable(params)
  skuList.value = res.data.list.map((item) => {
    return {
      ...item,
      key: item.id,
      label: item.skuName,
    }
  })
}
//===============点单================================
const creatOrder = ref({})
const dialogOrder = ref(false)
const num = ref(1)
const orderId = ref('')
const creatOrderLise = ref([])
//点击了点单操作
const handleCreat = (row) => {
  dialogOrder.value = true
  orderId.value = row.testMenuId
  formData.testMenuId = row.testMenuId
  formData.isAddMenu = row.isAddMenu
}
//点击点单change
const handleChange = (list) => {
  creatOrderLise.value = list.map((item) => {
    let skuItem = skuList.value.find((value) => {
      return value.id == item
    })
    return { ...skuItem, num: 1 }
  })
}
//总共多少钱
const sumMonery = computed(() => {
  return creatOrderLise.value.reduce(
    (sum, item) => sum + item.num * item.price,
    0
  )
})
//格式化时间为YY-MM-DD

const parseTime = (dates) => {
  const date = new Date(dates)
  const formattedTime = `${date.getFullYear()}-${(date.getMonth() + 1)
    .toString()
    .padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  return formattedTime
}
//点击了下单
const handdleOrderDetail = async (row) => {
  let params = {
    id: '1',
    datail: creatOrderLise.value.map((item) => {
      return {
        orderId: Number(orderId.value),
        price: item.price,
        skuName: item.skuName,
        num: item.num,
        isNew: formData.isAddMenu,
      }
    }),
  }
  let res = await addOrder(params)
  // formData.isAddMenu = 1
  let query = {
    isAddMenu: 1,
    testMenuId: formData.testMenuId,
  }
  await editItem(query)
  geTableList()
  dialogOrder.value = false
  changeValue.value = []
  creatOrderLise.value = []
}
//======================结账=======================================
const historyLis = ref([])
const dialogCheckout = ref(false)
const testMenuId = ref('')
const rowItem = ref({})
const handleOverMonery = async (row) => {
  rowItem.value = row
  testMenuId.value = row.testMenuId
  console.log(rowItem, 'rowItem')
  let params = {
    orderId: Number(row.testMenuId),
  }
  let res = await orderOver(params)
  historyLis.value = res.data.list.map((item) => {
    if (item.isNew == 1) {
      item.skuName += '(新加)'
    }
    return item
  })
  dialogCheckout.value = true
}
//点击结账按钮
const handdleOrderOver = async () => {
  deleteClick()
}
//总共多少钱
const sumOrderMonery = computed(() => {
  return historyLis.value.reduce((sum, item) => sum + item.num * item.price, 0)
})
//点击搜索
const search = () => {
  geTableList()
}
//点击新增
const handleAdd = () => {
  dialogTitle.value = '新增桌号'
  dialogFormVisible.value = true
}
//点击提交
const onSubmit = async (ruleFormRef) => {
  ruleFormRef.validate(async (valid, fields) => {
    if (valid) {
      dialogFormVisible.value = false
      let params = {
        num: Number(formData.num),
        people: formData.people,
        isAddMenu: 0,
      }
      if (dialogTitle.value == '修改桌号') {
        let query = {
          num: Number(formData.num),
          people: formData.people,
          testMenuId: formData.testMenuId,
        }
        await editItem(query)
        geTableList()
        formData.num = ''
        formData.people = ''
        formData.testMenuId = ''
      } else {
        await creatItem(params)
        geTableList()
        formData.num = ''
        formData.people = ''
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
//点击删除
const deleteClick = async (row) => {
  ElMessageBox.confirm('你确定要结账吗?', '提示!', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    let params = {
      orderId: Number(rowItem.value.testMenuId),
      totalPrice: sumOrderMonery.value.toString(),
      people: rowItem.value.people,
      num: rowItem.value.num,
      create_time: rowItem.value.create_time,
    }
    let res = createCenter(params)
    dialogCheckout.value = false
    formData.isAddMenu = ''
    await deleteItem(testMenuId.value)
    geTableList()
    ElMessage({
      type: 'success',
      message: '结账成功 !',
    })
  })
}
const handleEdit = async (row) => {
  console.log(row)

  // 编辑代码...
  let res = await getOne(row.testMenuId)
  // console.log(formData.num)
  formData.num = res.data.num
  formData.people = res.data.people
  formData.testMenuId = res.data.testMenuId
  dialogTitle.value = '修改桌号'
  dialogFormVisible.value = true
}
const cancel = (formData) => {
  formData.resetFields()
  dialogFormVisible.value = false
}

//点击每页数量
const handleSizeChange = async (size) => {
  searchData.pageSize = size
  geTableList()
}
//点击页码
const handleCurrentChange = async (currentPage) => {
  searchData.pageNum = currentPage
  geTableList()
}
//点击重置
const reset = () => {
  searchData.num = ''
  searchData.people = ''
  searchData.time = undefined
  geTableList()
}
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  // padding: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
:deep(.dialog-footer) {
  text-align: end;
}
</style>
